package com.lhy.tool.generator;

import com.lhy.tool.autoconfigation.GeneratorProperties;
import com.lhy.tool.database.DbColumnType;
import com.lhy.tool.database.Table;
import com.lhy.tool.database.TableColumn;
import com.lhy.tool.model.Clazz;
import com.lhy.tool.model.CrudBean;
import com.lhy.tool.model.CrudColumn;
import com.lhy.tool.model.JavaAttribute;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public abstract class AbstractModelGenerator extends AbstractJavaGenerator {

    private Set<String> packages;

    private List<CrudColumn> columns;

    private Table table;

    private boolean localDateFormatEnabled;

    @Override
    protected void writeJavaAttribute(CrudBean crudBean, GeneratorProperties generatorProperties) {
        table = crudBean.getTable();
        this.packages = table.getColumns().stream()
                .map(TableColumn::getColumnType)
                .map(DbColumnType::getPkg)
                .filter(StringUtils::hasText)
                .map(s -> s + ";")
                .collect(Collectors.toSet());
        this.localDateFormatEnabled = generatorProperties.getGlobalConfig().getLocalDateFormatEnabled();
        addDateFormatPackage();
        columns = crudBean.getColumns();
    }

    private void addDateFormatPackage() {
        boolean hasLocalTime = table.getColumns().stream().map(TableColumn::getColumnType).map(DbColumnType::getType).anyMatch(c -> "LocalDate".equals(c) || "LocalDateTime".equals(c));
        if (hasLocalTime && localDateFormatEnabled) {
            this.packages.add("org.springframework.format.annotation.DateTimeFormat;");
            this.packages.add("com.fasterxml.jackson.annotation.JsonFormat;");
        }
    }

    @Override
    protected Clazz curClazz(JavaAttribute javaAttribute) {
        return javaAttribute.getModel();
    }

    @Override
    protected String projectPath(GeneratorProperties.Project project) {
        return project.getJavaProjectPath();
    }

    @Override
    protected String templateName() {
        return "TemplateModel.java.ftl";
    }
}
